package com.shangqing.document_management.exception;

import com.shangqing.document_management.constant.EmBusinessError;
import com.shangqing.document_management.constant.Result;
import com.shangqing.document_management.constant.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;


@ControllerAdvice
@Slf4j
public class ExceptionHandle {
    @ExceptionHandler(value= MethodArgumentNotValidException.class)
    public Result handleVaildException(MethodArgumentNotValidException e){
        log.error("数据校验出现问题{}，异常类型：{}",e.getMessage(),e.getClass());
        BindingResult bindingResult = e.getBindingResult();
        Map<String,String> errorMap = new HashMap<>();
        bindingResult.getFieldErrors().forEach((fieldError)->{
            errorMap.put(fieldError.getField(),fieldError.getDefaultMessage());
        });
        return ResultUtil.error(EmBusinessError.UNKONW_ERROR.getCode(),EmBusinessError.UNKONW_ERROR.getMsg());
    }

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result handle(Exception e) {
        if (e instanceof BusinessException) {
            BusinessException businessException = (BusinessException) e;
            return ResultUtil.error(businessException.getCode(), businessException.getMessage());
        } else {
            log.error("系统异常" + e);
            return ResultUtil.error(-1, "未知错误");
        }

    }
}
